﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Coolite.Ext.Web;
using Newtonsoft.Json.Linq;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ExpertWaitingListControl : BaseUserControl<ExpertWaitingListControlViewModel>
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !Ext.IsAjaxRequest)
            {
                var loans = this.ViewModel.GetExpertWaitingList();
                this.loanStore.DataSource = loans;
                this.loanStore.DataBind();
                //-------------------------------------------------------------------------
                //var actionsList = from action in this.ViewModel.GetAvailableActions()
                //                  select new
                //                  {
                //                      DecisionID = Enums.ToString(action),
                //                      DecisionName = Enums.ToString(action,GetLocalResourceObject("LanguageIndex").ToInt32())
                //                  };
                Dictionary<int, string> decisionDic = new Dictionary<int, string>();
                decisionDic.Add(1, GetLocalResourceObject("ResDes").ToString());
                decisionDic.Add(2, GetLocalResourceObject("ReturnDes").ToString());

                var actionsList = from decition in decisionDic
                                  select new { DecisionID = decition.Key, DecisionName = decition.Value };


                this.storeDecisions1.DataSource = actionsList;
                this.storeDecisions1.DataBind();
            }
        }

        /// <summary>
        /// Handles the Command event of the gvLoans control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvLoans_Command(object sender, AjaxEventArgs args)
        {
            switch (args.ExtraParams["CommandName"])
            {
                case "ViewLoan":
                    this.RedirectFromThisPage("Loan", "createloan", "LoanID=" + args.ExtraParams["LoanID"]);
                    break;
            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["grvLoans"] != null)
            {
                string jsonString = e.ExtraParams["grvLoans"];
                JArray jarray = JSON.Deserialize(jsonString) as JArray;

                // Dictionary<string, int> actionTypeDic = Enums.ToNameKeyPaires(typeof(ActionTypes));
                List<int> loanDecisions = new List<int>();
                List<Guid> loansIDs = new List<Guid>();
                List<string> Notes = new List<string>();

                for (int i = 0; i < jarray.Count; i++)
                {
                    if (!string.IsNullOrEmpty(jarray[i]["DecisionID"].ToString().Trim('"')))
                    {
                        loansIDs.Add(jarray[i]["LoanID"].ToString().Trim('"').ToGuid());
                        loanDecisions.Add(jarray[i]["DecisionID"].ToString().Trim('"').ToInt32());
                        if (jarray[i]["Notes"] != null)
                            Notes.Add(jarray[i]["Notes"].ToString().Trim('"').Replace("\\n", "\r\n"));
                        else
                            Notes.Add(string.Empty);
                    }
                }


                if (loanDecisions.Count > 0)
                {
                    this.ViewModel.TakeLoanDecisions(loansIDs, loanDecisions, Notes);
                    RefreshControl();

                    if (LoansSubmitted != null)
                        LoansSubmitted(this, new AjaxEventArgs(new Coolite.Ext.Web.ParameterCollection()));
                }
            }
        }

        /// <summary>
        /// Refreshes the control.
        /// </summary>
        public void RefreshControl()
        {
            var loans = this.ViewModel.GetExpertWaitingList();
            this.loanStore.DataSource = loans;
            this.loanStore.DataBind();
        }

        /// <summary>
        /// Occurs when [loans submitted].
        /// </summary>
        public event EventHandler<AjaxEventArgs> LoansSubmitted;
    }
}